using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using LottieDemo.Models;
using LottieDemo.Services.Interfaces;
using Microsoft.Extensions.Logging;

namespace LottieDemo.ViewModels;

/// <summary>
/// 聊天窗口ViewModel
/// </summary>
public partial class ChatViewModel : ObservableObject
{
    private readonly IAiChatService _aiChatService;
    private readonly ILogger<ChatViewModel> _logger;

    /// <summary>
    /// 聊天消息集合
    /// </summary>
    public ObservableCollection<ChatMessage> Messages { get; } = new();

    /// <summary>
    /// 用户输入的消息
    /// </summary>
    [ObservableProperty]
    private string _inputMessage = string.Empty;

    /// <summary>
    /// 是否正在等待AI回复
    /// </summary>
    [ObservableProperty]
    private bool _isWaitingForResponse;

    /// <summary>
    /// 构造函数（通过DI注入）
    /// </summary>
    public ChatViewModel(IAiChatService aiChatService, ILogger<ChatViewModel> logger)
    {
        _aiChatService = aiChatService;
        _logger = logger;

        // 添加欢迎消息（不播放动画）
        Messages.Add(new ChatMessage(MessageType.Assistant, "你好！我是AI助手，有什么可以帮助你的吗？", isLoading: false));
    }

    /// <summary>
    /// 发送消息命令
    /// </summary>
    [RelayCommand(CanExecute = nameof(CanSendMessage))]
    private async Task SendMessageAsync()
    {
        if (string.IsNullOrWhiteSpace(InputMessage))
            return;

        var userMessage = InputMessage;
        InputMessage = string.Empty;

        _logger.LogInformation("用户发送消息: {Message}", userMessage);

        // 添加用户消息到列表
        Messages.Add(new ChatMessage(MessageType.User, userMessage));

        // 创建一个占位的AI消息（显示loading状态）
        var aiMessage = new ChatMessage(MessageType.Assistant, string.Empty, isLoading: true);
        Messages.Add(aiMessage);

        // 标记正在等待回复
        IsWaitingForResponse = true;

        try
        {
            // 调用AI服务获取回复
            var response = await _aiChatService.GetResponseAsync(userMessage);

            // 更新AI消息内容并隐藏loading
            aiMessage.Content = response;
            aiMessage.IsLoading = false;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取AI回复时发生错误");
            aiMessage.Content = "抱歉，获取回复时发生错误。";
            aiMessage.IsLoading = false;
        }
        finally
        {
            IsWaitingForResponse = false;
        }
    }

    /// <summary>
    /// 判断是否可以发送消息
    /// </summary>
    private bool CanSendMessage()
    {
        return !string.IsNullOrWhiteSpace(InputMessage) && !IsWaitingForResponse;
    }

    /// <summary>
    /// InputMessage属性变化时重新评估命令可执行状态
    /// </summary>
    partial void OnInputMessageChanged(string value)
    {
        SendMessageCommand.NotifyCanExecuteChanged();
    }

    /// <summary>
    /// IsWaitingForResponse属性变化时重新评估命令可执行状态
    /// </summary>
    partial void OnIsWaitingForResponseChanged(bool value)
    {
        SendMessageCommand.NotifyCanExecuteChanged();
    }
}
